package com.newegg.hardware.benchmark.service;

import java.util.List;
import com.newegg.hardware.benchmark.model.MarkCount;

public class MarkMean {
	
	public static Range getMarkRange(List<MarkCount> markcounts) {
		if(markcounts == null || markcounts.size() == 0) { return null; }
		int mean = mean(markcounts);
		int size = size(markcounts);
		double deviation = deviation(markcounts, mean, size);
		int ratio = 10;
		Range range = new Range((int)(mean - ratio * deviation), (int)(mean + ratio * deviation), mean);
		return range;
	}
	
	static int mean(List<MarkCount> markcounts) {
		long mark = 0;
		int size = 0;
		for (MarkCount markCount : markcounts) {
			mark += markCount.getMark() * markCount.getCount();
			size += markCount.getCount();
		}
		return (int) (mark / size);
	}
	
	static int size(List<MarkCount> markcounts) {
		int size = 0;
		for (MarkCount markCount : markcounts) {
			size += markCount.getCount();
		}
		return size;
	}
	
	static double deviation(List<MarkCount> markcounts, int mean, int size) {
		long s = 0;
		for (MarkCount markCount : markcounts) {
			s += (markCount.getMark() - mean) * (markCount.getMark() - mean) * markCount.getCount();
		}
		return Math.sqrt(s / size);
	}
	
	static class Range{
		public int start;
		public int end;
		public int mean;

		public Range(int start, int end, int mean) {
			this.start = start;
			this.end = end;
			this.mean = mean;
		}

		@Override
		public String toString() {
			return String.format("Range [start=%s, end=%s, mean=%s]", start, end, mean);
		}
	}
}